package org.jeecg.modules.sggg.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.*;
import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 设备关联表
 * @Author: jeecg-boot
 * @Date: 2023-03-19
 * @Version: V1.0
 */
@Api(tags = "设备关联表")
@RestController
@RequestMapping("/deviceRelevance/sgDeviceRelevance")
@Slf4j
public class SgDeviceRelevanceController extends JeecgController<SgDeviceRelevance, ISgDeviceRelevanceService> {
    @Autowired
    private ISgDeviceRelevanceService sgDeviceRelevanceService;

    @Autowired
    private ISgDeviceService sgDeviceService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISgBlutdruckRecordService sgBlutdruckRecordService;

    @Autowired
    private ISgGlucoseRecordService sgGlucoseRecordService;

    @Autowired
    private SysRoleController sysRoleController;

    @Autowired
    private ISysDepartService sysDepartController;


    /**
     * 分页列表查询
     *
     * @param sgDeviceRelevance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "设备关联表-分页列表查询")
    @ApiOperation(value = "设备关联表-分页列表查询", notes = "设备关联表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgDeviceRelevance>> queryPageList(SgDeviceRelevance sgDeviceRelevance,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        sgDeviceRelevance.setIsDelete(0);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前登录用户的角色
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgDeviceRelevance.setResponsibleAgencies(responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgDeviceRelevance.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        Page<SgDeviceRelevance> page = new Page<>(pageNo, pageSize);
        IPage<SgDeviceRelevance> pageList = sgDeviceRelevanceService.getDoctorAuthority(page, sysUser.getId(),
                sysUser.getOrgCode(), roleCode, sgDeviceRelevance, sgDeviceRelevance.getSysOrgCode());
        return Result.ok(pageList);
    }


    /**
     * @param sgDeviceRelevance
     * @return
     * @ApiOperation(value = "设备关联表-分页列表查询", notes = "设备关联表-分页列表查询")
     * @GetMapping(value = "/listTo")
     * public Result<IPage<SgDeviceRelevance>> queryPageListTo(SgDeviceRelevance sgDeviceRelevance,
     * @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
     * @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
     * HttpServletRequest req) {
     * LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
     * sgDeviceRelevance.setSysOrgCode(sysUser.getOrgCode());
     * Page<SgDeviceRelevance> page = new Page<SgDeviceRelevance>(pageNo, pageSize);
     * IPage<SgDeviceRelevance> pageList = sgDeviceRelevanceService.queryPageListBySql(page, sgDeviceRelevance);
     * return Result.OK(pageList);
     * }
     * <p>
     * /**
     * 添加
     */
    @AutoLog(value = "设备关联表-添加")
    @ApiOperation(value = "设备关联表-添加", notes = "设备关联表-添加")
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgDeviceRelevance sgDeviceRelevance) {
        List<SgDeviceRelevance> sgDeviceRelevance1 = sgDeviceRelevanceService.list(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", sgDeviceRelevance.getSerialNumber()).eq("is_delete", 0));
        if (sgDeviceRelevance1.size() > 0) {
            return Result.error("绑定失败,该设备已被绑定！");
        }
        sgDeviceRelevanceService.save(sgDeviceRelevance);
        return Result.OK("绑定成功！");
    }

    /**
     * 编辑
     *
     * @param sgDeviceRelevance
     * @return
     */
    @AutoLog(value = "设备关联表-编辑")
    @ApiOperation(value = "设备关联表-编辑", notes = "设备关联表-编辑")
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgDeviceRelevance sgDeviceRelevance) {
        sgDeviceRelevanceService.updateById(sgDeviceRelevance);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备关联表-通过id删除")
    @ApiOperation(value = "设备关联表-通过id删除", notes = "设备关联表-通过id删除")
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        SgDeviceRelevance sgDeviceRelevance = new SgDeviceRelevance();
        sgDeviceRelevance.setId(id);
        sgDeviceRelevance.setIsDelete(1);
        sgDeviceRelevanceService.updateById(sgDeviceRelevance);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "设备关联表-批量删除")
    @ApiOperation(value = "设备关联表-批量删除", notes = "设备关联表-批量删除")
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        String[] data = ids.split(",");
        for (int i = 0; i < data.length; i++) {
            SgDeviceRelevance sgDeviceRelevance = new SgDeviceRelevance();
            sgDeviceRelevance.setId(data[i]);
            sgDeviceRelevance.setIsDelete(1);
            sgDeviceRelevanceService.updateById(sgDeviceRelevance);
        }
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "设备关联表-通过id查询")
    @ApiOperation(value = "设备关联表-通过id查询", notes = "设备关联表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgDeviceRelevance> queryById(@RequestParam(name = "id", required = true) String id) {
        SgDeviceRelevance sgDeviceRelevance = sgDeviceRelevanceService.getById(id);
        if (sgDeviceRelevance == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgDeviceRelevance);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgDeviceRelevance
     */
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgDeviceRelevance sgDeviceRelevance) {
        return super.exportXls(request, sgDeviceRelevance, SgDeviceRelevance.class, "设备关联表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("deviceRelevance:sg_device_relevance:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgDeviceRelevance.class);
    }


    /**
     * 设备绑定
     *
     * @param sgDeviceRelevance
     * @return
     */
    @AutoLog(value = "设备关联表-设备绑定")
    @ApiOperation(value = "设备关联表-设备绑定", notes = "设备关联表-设备绑定")
    @PostMapping(value = "/binding")
    public Result<String> binding(@RequestBody SgDeviceRelevance sgDeviceRelevance) {
        if (sgDeviceRelevanceService.list(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", sgDeviceRelevance.getSerialNumber()).eq("is_delete", 0)).size() > 0) {
            return Result.error("该设备已被绑定！");
        }
        sgDeviceRelevanceService.save(sgDeviceRelevance);

        SgDevice sgDevice = sgDeviceService.getById(sgDeviceRelevance.getDeviceId());
        sgDevice.setStock(sgDevice.getStock() - 1);
        sgDeviceService.updateById(sgDevice);
        return Result.OK("绑定成功！");
    }

    /**
     * 设备解绑
     *
     * @param sgDeviceRelevance
     * @return
     */
    @AutoLog(value = "设备关联表-设备解绑")
    @ApiOperation(value = "设备关联表-设备绑定", notes = "设备关联表-设备解绑")
    @PostMapping(value = "/unbinding")
    public Result<String> unbinding(@RequestBody SgDeviceRelevance sgDeviceRelevance) {
        sgDeviceRelevance.setIsDelete(1);
        sgDeviceRelevanceService.updateById(sgDeviceRelevance);
        SgDevice sgDevice = sgDeviceService.getById(sgDeviceRelevance.getDeviceId());
        sgDevice.setStock(sgDevice.getStock() + 1);
        sgDeviceService.updateById(sgDevice);
        return Result.OK("解绑成功！");
    }

    /**
     * 查询某个居民所绑定的设备
     *
     * @param sgDeviceRelevance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "设备关联表-查询某个居民所绑定的设备", notes = "设备关联表-查询某个居民所绑定的设备")
    @GetMapping(value = "/queryByMemberId")
    public Result<IPage<SgDeviceRelevance>> queryByMemberId(SgDeviceRelevance sgDeviceRelevance,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "99") Integer pageSize,
                                                            HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SgDeviceRelevance> queryWrapper = QueryGenerator.initQueryWrapper(sgDeviceRelevance, req.getParameterMap());
        queryWrapper.eq("member_id", sgDeviceRelevance.getMemberId());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq(sgDeviceRelevance.getType() != null, "type", sgDeviceRelevance.getType());
        queryWrapper.eq("sys_org_code", sysUser.getOrgCode());
        Page<SgDeviceRelevance> page = new Page<>(pageNo, pageSize);
        IPage<SgDeviceRelevance> pageList = sgDeviceRelevanceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询某个居民所绑定的设备/不分页
     *
     * @param sgDeviceRelevance
     * @return
     */
    @ApiOperation(value = "设备关联表-查询某个居民所绑定的设备/不分页", notes = "设备关联表-查询某个居民所绑定的设备/不分页")
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgDeviceRelevance>> queryByMemberId(SgDeviceRelevance sgDeviceRelevance) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<SgDeviceRelevance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", sgDeviceRelevance.getMemberId());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq(sgDeviceRelevance.getType() != null, "type", sgDeviceRelevance.getType());
        List<SgDeviceRelevance> pageList = sgDeviceRelevanceService.list(queryWrapper);
        pageList.forEach(item -> {
            item.setDeviceName(sgDeviceService.getById(item.getDeviceId()).getName());
        });
        return Result.OK(pageList);
    }

    /**
     * 根据患者id和设备类型查询绑定的设备
     *
     * @param memberId
     * @return
     */
    @GetMapping("/getMemberDevice")
    public Result<List<SgDeviceRelevance>> getMemberDevice(String memberId, Integer type) {
        List<SgDeviceRelevance> sgDeviceRelevances = sgDeviceRelevanceService.list(new QueryWrapper<SgDeviceRelevance>().eq("type", type).eq("member_id", memberId).eq("is_delete", 0));
        return Result.ok(sgDeviceRelevances);
    }

    /**
     * 根据序列号查询居民id
     *
     * @param
     * @return
     */
    //@AutoLog(value = "设备关联表-通过id查询")
    @ApiOperation(value = "设备关联表-根据序列号查询居民id", notes = "设备关联表-根据序列号查询居民id")
    @GetMapping(value = "/querySerialNumber")
    public Result<SgDeviceRelevance> querySerialNumber(@RequestParam(name = "serialNumber", required = true) String serialNumber) {
        List<SgDeviceRelevance> sgDeviceRelevance = sgDeviceRelevanceService.list(
                new QueryWrapper<SgDeviceRelevance>()
                        .eq("serial_number", serialNumber)
                        .eq("is_delete", 0)
        );
        SgDeviceRelevance returnData = new SgDeviceRelevance();
        if (sgDeviceRelevance.size() > 0) {
            for (SgDeviceRelevance isDocters : sgDeviceRelevance) {
                if (isDocters.getIsDoctorsDevice() != null) {
                    if (isDocters.getIsDoctorsDevice() == 0) {
                        returnData = isDocters;
                        return Result.OK("查询成功!", returnData);
                    } else if (isDocters.getIsDoctorsDevice() == 1) {
                        returnData = isDocters;
                    }
                } else {
                    returnData = isDocters;
                }
            }
        } else {
            return Result.error("未找到对应数据!");
        }
        return Result.OK("查询成功!", returnData);
    }

    /**
     * 随访连接设备
     *
     * @param idCard
     * @param type
     * @return
     * @throws Exception
     */
    @GetMapping("/connectDevice")
    public Result<String> connectDevice(String idCard, Integer type) throws Exception {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id_card", idCard));
        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(redisUtil.get("boundDevice:" + sysUser.getId())));
        // 居民有没有绑定医生的设备
        SgDeviceRelevance sgDeviceRelevance = new SgDeviceRelevance();
        if (type == 0) {
            sgDeviceRelevance = sgDeviceRelevanceService.getOne(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", jsonObject.getString("xueya")).eq("is_delete", 0));
        } else {
            sgDeviceRelevance = sgDeviceRelevanceService.getOne(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", jsonObject.getString("xuetang")).eq("is_delete", 0));
        }
        if (sgDeviceRelevance == null) {
            // 有没有绑定其他设备
            isQT(jsonObject, sgMember, type);
        } else {
            if (sgMember.getId() == sgDeviceRelevance.getMemberId()) {
                return Result.ok("连接成功！");
            } else {
                sgDeviceRelevanceService.removeById(sgDeviceRelevance);
                isQT(jsonObject, sgMember, type);
            }
        }
        return Result.ok("连接成功！");
    }

    /**
     * 随访连接设备后，刷新获取测量值
     *
     * @param idCard
     * @param type
     * @return
     */
    @GetMapping("/getFollowUpDate")
    public Result<JSONObject> getFollowUpDate(String idCard, Integer type) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SgMember sgMember = sgMemberService.getOne(new QueryWrapper<SgMember>().eq("id_card", idCard));
        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(redisUtil.get("boundDevice:" + sysUser.getId())));
        SgBlutdruckRecord sgBlutdruckRecord = new SgBlutdruckRecord();
        SgGlucoseRecord sgGlucoseRecord = new SgGlucoseRecord();
        if (type == 0) {
            sgBlutdruckRecord = sgBlutdruckRecordService.getOne(new QueryWrapper<SgBlutdruckRecord>().eq("device_id", jsonObject.getString("xueya")).eq("member_id", sgMember.getId()).ge("measuring_time", LocalDate.now()).le("measuring_time", LocalDateTime.now()));
            if (sgBlutdruckRecord != null) {
                jsonObject.put("dbpval", sgBlutdruckRecord.getDbpval());
                jsonObject.put("sbpval", sgBlutdruckRecord.getSbpval());
                jsonObject.put("heartRate", sgBlutdruckRecord.getHeartRate());
                sgDeviceRelevanceService.remove(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", jsonObject.getString("xueya")).eq("member_id", sgMember.getId()));
            } else {
                jsonObject.put("error", "请先进行测量！");
            }
        } else {
            sgGlucoseRecord = sgGlucoseRecordService.getOne(new QueryWrapper<SgGlucoseRecord>().eq("device_id", jsonObject.getString("xuetang")).eq("member_id", sgMember.getId()).ge("measuring_time", LocalDate.now()).le("measuring_time", LocalDateTime.now()));
            if (sgGlucoseRecord != null) {
                jsonObject.put("gluval", sgGlucoseRecord.getGluval());
                sgDeviceRelevanceService.remove(new QueryWrapper<SgDeviceRelevance>().eq("serial_number", jsonObject.getString("xuetang")).eq("member_id", sgMember.getId()));
            } else {
                jsonObject.put("error", "请先进行测量！");
            }
        }
        return Result.ok(jsonObject);
    }

    /**
     * 居民有没有绑定其他设备
     *
     * @param jsonObject
     * @param sgMember
     * @param type
     */
    public void isQT(JSONObject jsonObject, SgMember sgMember, Integer type) {
        List<SgDeviceRelevance> isQT = sgDeviceRelevanceService.list(new QueryWrapper<SgDeviceRelevance>().eq("member_id", sgMember.getId()));
        SgDeviceRelevance deviceRelevance = new SgDeviceRelevance();
        if (type == 0) {
            deviceRelevance.setSerialNumber(jsonObject.getString("xueya"));
            SgDevice sgDevice = sgDeviceService.getOne(new QueryWrapper<SgDevice>().eq("type", 0).eq("is_delete", 0));
            deviceRelevance.setDeviceId(sgDevice.getId());
            deviceRelevance.setType(0);
        } else {
            deviceRelevance.setSerialNumber(jsonObject.getString("xuetang"));
            SgDevice sgDevice = sgDeviceService.getOne(new QueryWrapper<SgDevice>().eq("type", 1).eq("is_delete", 0));
            deviceRelevance.setDeviceId(sgDevice.getId());
            deviceRelevance.setType(1);
        }
        deviceRelevance.setMemberId(sgMember.getId());
        if (isQT.size() >= 0) {
            deviceRelevance.setIsDoctorsDevice(0);
        }
        sgDeviceRelevanceService.save(deviceRelevance);
    }

    /**
     * 数据看板-设备发放数量
     *
     * @param type 设备类型 0血压计/1血糖仪
     * @return
     */
    @GetMapping("/provideDeviceCount")
    public Result<List<SgDeviceRelevance>> provideDeviceCount(String type) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            // 机构管理员，查询的是本机构下的数据
            List<SgDeviceRelevance> count = sgDeviceRelevanceService.provideDeviceCount(type, null, null, roleCode.contains("dept_manage") ? sysUser.getOrgCode() : null);
            return Result.ok(count);
        }
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        List<SgDeviceRelevance> count = sgDeviceRelevanceService.provideDeviceCount(type, sysUser.getId(), responsibleAgencies, null);
        return Result.ok(count);
    }
}
